package com.dongyimai.oauth.token;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateCrtKey;
import java.util.HashMap;
import java.util.Map;

public class AdminToken {
    /*** 管理员令牌发放 */
    public static String createAdminToken() {
        // 加载证书 读取类路径中的文件
        ClassPathResource resource = new ClassPathResource("dongyimai.jks");
        // 读取证书数据,加载读取证书数据
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, "dongyimai".toCharArray());
        // 获取证书中的一对秘钥
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("dongyimai","dongyimai".toCharArray());
        // 获取私钥
        RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey)keyPair.getPrivate();
        // 创建令牌，需要私钥 （RSA算法） // jwt ==> 头，载体，证书
        Map<String,Object> payload = (Map<String,Object>) new HashMap<String, Object>();
        payload.put("name","xiaobai");
        payload.put("addresss","bj"); //对比定义
        payload.put("authorities",new String[]{"admin","user"});
        Jwt jwt = JwtHelper.encode(JSON.toJSONString(payload), new RsaSigner(privateKey));
        //令牌
        String token = jwt.getEncoded();
        return token;
        }
    }
